package edu.friday.common.security.service;

import edu.friday.common.exception.CustomException;
import edu.friday.common.exception.user.UserPasswordNotMatchException;
import edu.friday.common.security.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class SysLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;
    public String login(String username, String password, String uuid) {
        Authentication authenticate = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (AuthenticationException e) {
            if(e instanceof BadCredentialsException)
                throw new UserPasswordNotMatchException();
            else throw new CustomException(e.getMessage());
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        return tokenService.creteToken(loginUser);
    }
}
